package ThreadDemo1;

import java.util.concurrent.PriorityBlockingQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 故我
 * Date: 2023-10-12
 * Time: 18:39
 */

class MyTask implements Comparable<MyTask> {
    private Runnable runnable;  //放入线程中的任务
    private long time;//还剩下多少时间就执行这个任务

    public MyTask(Runnable runnable, long time) {
        this.runnable = runnable;
        this.time = time;
    }

    public long GetTime() {
        return time;
    }

    //执行任务
    public void Run() {
        runnable.run();
    }

    //实现接口 Comparetor  按时间比较
    @Override
    public int compareTo(MyTask o) {
        /* this > o return < 0  反之*/
        return (int) (this.time - o.time);
    }
}

class MyTimer {
    private Thread t = null;//扫描线程
    private PriorityBlockingQueue<MyTask> queue = new PriorityBlockingQueue<>();//存储任务的阻塞优先级队列
    private Object lock = new Object();//用于专门加锁

    public void schedule(Runnable runnable, long time) {
        MyTask t = new MyTask(runnable, System.currentTimeMillis() + time);
        queue.put(t);
        //唤醒扫描线程
        synchronized (lock) {
            lock.notify();
        }
    }

    //取队列的首个元素，判断时间，时间到了就运行，没有就继续放回队列中
    public MyTimer() {
        t = new Thread() {
            @Override
            public void run() {
                while (true) {
                    try {
                        synchronized (lock) { //为了避免线程切换出去，导致时间超时，直接整个加锁
                            MyTask task = queue.take();
                            //与当前时间进行比较
                            long timer = System.currentTimeMillis();
                            if (timer < task.GetTime()) {
                                //此时还没有到达指定的时间  13:00   14:00
                                queue.put(task);
                                //put之后，为了不必要一直取出任务直接，wait时间，put任务会唤醒线程

                                lock.wait(task.GetTime() - timer);

                            } else {
                                //时间到了，执行任务
                                task.Run();
                            }
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        t.start();
    }
}

public class ThreadDemo24 {
    public static void main(String[] args) {
        MyTimer myTimer = new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("任务 1");
            }
        }, 2000);

        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("任务 2");
            }
        }, 3000);
        //线程还在扫描，所以程序还没有停止下来
    }
}
